package com.miku.project.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.miku.mikuapicommon.model.entity.DailyCheckIn;
import com.miku.project.common.BaseResponse;
import com.miku.project.common.ErrorCode;
import com.miku.project.common.ResultUtils;
import com.miku.project.exception.BusinessException;
import com.miku.project.model.vo.UserVO;
import com.miku.project.service.DailyCheckInService;
import com.miku.project.service.UserService;
import com.miku.project.utils.RedissonLockUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.miku.project.constant.DailyCheckConstance.DAILY_CHECK_LOCK;

@RestController
@RequestMapping("/dailyCheckIn")
@Slf4j
@Api(tags = "每日签到")
public class DailyCheckInController {
    @Resource
    private UserService userService;
    @Resource
    private RedissonLockUtil redissonLockUtil;
    @Resource
    private DailyCheckInService dailyCheckInService;


    /**
     * 签到
     * @param request
     * @return
     */
    @PostMapping("/doCheckIn")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("签到")
    public BaseResponse<Boolean> doDailyCheckIn(HttpServletRequest request){
        UserVO loginUser = userService.getLoginUser(request);
        String redissonLock=(DAILY_CHECK_LOCK+loginUser.getId());
        return redissonLockUtil.redissonDistributedLocks(redissonLock,()->{

            // 判断是否已经签到
            DailyCheckIn dailyCheckIn = dailyCheckInService.getOne(Wrappers.<DailyCheckIn>lambdaQuery()
                    .eq(DailyCheckIn::getId, loginUser.getId()));
            if (ObjectUtils.isNotEmpty(dailyCheckIn)){
               throw new BusinessException(ErrorCode.PARAMS_ERROR,"今日已签到");
            }
            dailyCheckIn=new DailyCheckIn();
            dailyCheckIn.setUserId(loginUser.getId());
            // 签到增加积分个数
            dailyCheckIn.setAddPoints(10L);
            boolean save = dailyCheckInService.save(dailyCheckIn);
            int points = dailyCheckIn.getAddPoints().intValue();
            //签到用户表金额增加
            boolean addWalletBalance = userService.addWalletBalance(loginUser.getId(), points);
            boolean result = save & addWalletBalance;
            if (!result){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"签到失败");
            }
            return ResultUtils.success(true);
        },"签到失败");
    }
}
